package com.atguigu.flink.wordcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2023/3/31
 *
 *     程序在idea本地运行后，通过webUI查看程序运行的参数。
 *          打包时，不需要。集群上安装的flink，自带功能。
 *          在idea运行，引入依赖！
 *
 */
public class Demo5_WebUIDemo
{
    public static void main(String[] args) throws Exception {

        //设置idea本地运行时，绑定的端口。 在外部通过浏览器才能访问端口！
        Configuration conf = new Configuration();
        //key是固定的，参考 https://nightlies.apache.org/flink/flink-docs-release-1.16/docs/deployment/config/#hosts-and-ports
        conf.setInteger("rest.port",3333);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        //env.setParallelism(4);

        DataStreamSource<String> ds = env.socketTextStream("hadoop102", 8888);

        SingleOutputStreamOperator<Tuple2<String, Integer>> ds2 = ds
            .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>()
            {
                @Override
                public void flatMap(String line, Collector<Tuple2<String, Integer>> out) throws Exception {

                    String[] words = line.split(" ");
                    for (String word : words) {
                        out.collect(Tuple2.of(word, 1));
                    }
                }
            });
        ds2
            .keyBy(new KeySelector<Tuple2<String, Integer>, String>()
            {
                @Override
                public String getKey(Tuple2<String, Integer> value) throws Exception {
                    return value.f0;
                }
            })
            .sum(1)
            .print();


        /*
            把代码翻译为JobGraph
            把job信息（JobGraph）提交到 集群(JobManager)
         */
        env.execute();

    }
}
